package com.jokul.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jokul.model.Account;
import com.jokul.service.UserService;

/**
 *@author: jokul
 *@2013-3-7 下午4:05:56
 */
@WebServlet("/register.do")
public class Register extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    private final String SUCCESS_VIEW = "success.jsp";
    private final String ERROR_VIEW = "error.jsp";
    
    private UserService userService;
	
	public void init() throws ServletException {
		userService = (UserService) getServletContext().getAttribute("userService");
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	String email = request.getParameter("email");
    	String username = request.getParameter("username");
    	String password = request.getParameter("password");
    	String confirmedPasswd = request.getParameter("confirmedPasswd");
    	
    	Account account = new Account();
    	account.setName(username);
    	account.setPassword(password);
    	account.setEmail(email);
    	
    	List<String> errors = new ArrayList<String>();    	
    	if(isInvalidEmail(email)) {
    		errors.add("未填写邮件或邮件格式不正确！");
    	}
    	if(isInvalidUsername(account)) {
    		errors.add("用户名为空或已存在！");
    	}
    	if(isInvalidPassword(password, confirmedPasswd)) {
    		errors.add("请确定密码符合格式并再次确认密码！");
    	}
    	
    	String resultPage = ERROR_VIEW;
    	if(!errors.isEmpty()) {
    		request.setAttribute("errors", errors);
    	}else {
    		int result = userService.addAccount(new Account(username, password, email));
    		if(result > 0) {
    			resultPage = SUCCESS_VIEW;
    		}
    		request.setAttribute("username", username);
    	}
    	
    	request.getRequestDispatcher(resultPage).forward(request, response);
    }

    private boolean isInvalidEmail(String email) {
        return email == null
                || !email.matches("^[_a-z0-9-]+([.]"
                        + "[_a-z0-9-]+)*@[a-z0-9-]+([.][a-z0-9-]+)*$");
    }

    private boolean isInvalidUsername(Account account) {
    	return userService.isUserExisted(account);
    }

    private boolean isInvalidPassword(String password, String confirmedPasswd) {
        return password == null || password.length() < 6
                || password.length() > 16 || !password.equals(confirmedPasswd);
    }
}
